<template>
  <div class="dormitory-update-container">
    <el-form 
      :model="formData" 
      :rules="rules" 
      ref="formRef" 
      label-width="100px" 
      class="demo-form"
    >
      <el-form-item label="ID">
        <el-input v-model="formData.id" disabled />
      </el-form-item>
      
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      
      <el-form-item label="联系电话" prop="telephone">
        <el-input v-model="formData.telephone" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">立即修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dormitoryApi } from '@/api/dormitory'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)

const formData = ref({
  id: '',
  buildingId: '',
  name: '',
  type: '',
  telephone: ''
})

const rules = {
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择几人间', trigger: 'change' }
  ]
}

// 获取宿舍详情
const fetchDormitoryDetail = async (id) => {
  try {
    const res = await dormitoryApi.getDormitoryById(id)
    formData.value = res.data
  } catch (error) {
    ElMessage.error('获取宿舍信息失败: ' + error.message)
    router.push('/dormitoryManager')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    const res = await dormitoryApi.updateDormitory(formData.value)
    
    if (res.code === 0) {
      await ElMessageBox.alert(`${formData.value.name}修改成功`, '提示', {
        confirmButtonText: '确定',
        callback: () => {
          router.push('/dormitoryManager')
        }
      })
    } else {
      ElMessage.error(res.message || '修改失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('修改失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
}

onMounted(() => {
  if (route.query.id) {
    fetchDormitoryDetail(route.query.id)
  } else {
    ElMessage.warning('缺少宿舍ID参数')
    router.push('/dormitoryManager')
  }
})
</script>

<style scoped>
.dormitory-update-container {
  margin: 60px auto;
  width: 500px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.demo-form {
  margin-top: 20px;
}
</style>